import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.hei.kml.Template;
import com.hei.kml.Waylines;

import java.io.File;
import java.nio.charset.Charset;

public class Serializer {
	public static void main(String[] args) {
		File kmzFile = createTmpKmzFile(
				FileUtil.readString("tst/wpmz.req/template.json", Charset.defaultCharset())
				, FileUtil.readString("tst/wpmz.req/waylines.json", Charset.defaultCharset())
		);
		FileUtil.copy(kmzFile.toPath(), FileUtil.file("../" + System.currentTimeMillis() + "/test.kmz")
		                                        .toPath());
		System.out.println(kmzFile);
	}

	public static File createTmpKmzFile(String templateDocument, String waylinesDocument) {
		// 创建临时文件夹wpmz，并生成子文件template.kml waylines.kml
		String wpmz = FileUtil.getTmpDirPath() + "/" + System.currentTimeMillis() + "/wpmz";

		if (StrUtil.isNotBlank(templateDocument)) {
			String template = new Template().fromJSON(templateDocument).toKML();
			FileUtil.writeString(template, FileUtil.file(wpmz + "/template.kml"), Charset.defaultCharset());
		}

		if (StrUtil.isNotBlank(waylinesDocument)) {
			String waylines = new Waylines().fromJSON(waylinesDocument).toKML();
			FileUtil.writeString(waylines, FileUtil.file(wpmz + "/waylines.kml"), Charset.defaultCharset());
		}

		// 压缩临时文件夹wpmz
		File kmz = ZipUtil.zip(wpmz, wpmz + ".kmz", true);

		// 删除临时文件夹wpmz
		FileUtil.del(wpmz);
		return kmz;
	}

}
